package com.applink.sell_proof.database.table;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;

import com.applink.sell_proof.EMarketing;
import com.applink.sell_proof.database.EMarketingContentProvider;
import com.applink.sell_proof.model.Product;

public class ProductModelDBHelper {

	public static final String TABLE_NAME = "model_table";
	public static final String ID = "id";

	public static final String MODEL_CATEGORY = "model_category";
	public static final String MODEL_NAME = "model_name";
	public static final String MODEL_NO = "model_no";

	public static final String SQL_EXCUTE = "CREATE TABLE " + TABLE_NAME + "("
			+ ID + " integer default 0 primary key ," + MODEL_CATEGORY
			+ " text default '' ," + MODEL_NAME + " text default '' ,"
			+ MODEL_NO + " text default '');";

	public static void insertNewModels(final List<HashMap<String, String>> data) {

		final ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		new Thread() {
			@Override
			public void run() {
				for (HashMap<String, String> hm : data) {

					ContentValues values = new ContentValues();

					values.put(ID, hm.get(ID));
					values.put(MODEL_CATEGORY, hm.get(MODEL_CATEGORY));
					values.put(MODEL_NAME, hm.get(MODEL_NAME));
					values.put(MODEL_NO, hm.get(MODEL_NO));

					try {
						resolver.insert(
								EMarketingContentProvider.MODEL_CONTENT_URI,
								values);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	public static List<Product> searchProduct(String keyword) {

		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		Cursor cursor;

		if (keyword.equals(""))
			cursor = resolver.query(
					EMarketingContentProvider.MODEL_CONTENT_URI, null, null,
					null, null);
		else
			cursor = resolver.query(
					EMarketingContentProvider.MODEL_CONTENT_URI, null, "("
							+ MODEL_NAME + " LIKE ?) OR " + "(" + MODEL_NO
							+ " LIKE ?) ", new String[] { "%" + keyword + "%",
							"%" + keyword + "%" }, null);

		List<Product> pds = new ArrayList<Product>();

		if (cursor != null) {
			try {
				while (cursor.moveToNext()) {
					Product p = createModelFromCursor(cursor);

					pds.add(p);
				}
			} finally {
				cursor.close();
			}
		}
		return pds;
	}

	private static Product createModelFromCursor(Cursor c) {
		Product p = new Product();

		p.setProductId(c.getInt(c.getColumnIndex(ID)));
		p.setModelName(c.getString(c.getColumnIndex(MODEL_NAME)));
		p.setModelNo(c.getString(c.getColumnIndex(MODEL_NO)));
		p.setCatName(c.getString(c.getColumnIndex(MODEL_CATEGORY)));

		return p;
	}
}
